/**
 * Copyright (c) 2008 Trent Hoeppner
 * 
 * This file is part of BillCalc.
 * 
 * BillCalc is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * BillCalc is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with BillCalc.  If not, see <http://www.gnu.org/licenses/>.
 **/

package com.trentech.billcalc.event;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.Date;

import testcases.MainTest;

import com.trentech.billcalc.Biller;
import com.trentech.billcalc.FinanceManager;
import com.trentech.billcalc.Resident;
import com.trentech.billcalc.gui.EventEditor;


/**
 * Event represents change in the status of the people or finances of the 
 * apartment.
 */
public abstract class Event implements Comparable<Event> {
    
    /**
     * The object which is used to manage listeners and fire events for 
     * property changes.
     */
    private PropertyChangeSupport support = new PropertyChangeSupport(this);
    
    
    /**
     * Indicates whether this is saved to the events file.  Any changes to this
     * Event will make this variable false until it is resaved.
     */
    private boolean saved;
    
    
    /**
     * The date that this happened.
     */
    private Date date;
    
    
    /**
     * The name of the primary person or biller that this happened to.
     * Subclasses may wish to define a secondary name if there is 
     * interaction between two people.
     */
    private String name;
    
    
    /**
     * True if this event was generated, and can safely be deleted.  Default is 
     * false.
     */
    private boolean generated;
    
    
    /**
     * Constructor for Event.
     * 
     * @param   date    the date of the event.  Cannot be null.
     * @param   name    the name of the primary person or biller for this 
     *                  event.  Cannot be null or empty.
     */
    public Event(Date date, String name) {
        if (date == null) {
            throw new NullPointerException("date");
        }
        if (date == null) {
            throw new NullPointerException("name");
        }
        this.date = date;
        this.name = name;
        this.saved = false;
        
        this.generated = false;
    }
    
    
    /**
     * Adds the given PropertyChangeListener to this.
     * 
     * @param   l   the listener to add.  Cannot be null.
     */
    public void addPropertyChangeListener(PropertyChangeListener l) {
        support.addPropertyChangeListener(l);
    }
    
    
    /**
     * Removes the given PropertyChangeListener from this.
     * 
     * @param   l   the listener to remove.  Cannot be null.
     */
    public void removePropertyChangeListener(PropertyChangeListener l) {
        support.removePropertyChangeListener(l);
    }
    
    
    /**
     * Returns the support object that can be used to fire PropertyChangeEvents.
     * 
     * @return  the object that can be used to fire PropertyChangeEvents.  Will
     *          not be null.
     */
    PropertyChangeSupport getSupport() {
        return support;
    }


    /**
     * {@inheritDoc}
     */
    public int compareTo(Event other) {
        int timeDiff = compareLongs(getDate().getTime(), other.getDate().getTime());
        if (timeDiff != 0) {
            return timeDiff;
        }
        
        int stringComp = getName().compareTo(other.getName());
        if (stringComp != 0) {
            return stringComp;
        }
        
        return 0;
    }
    
    
    /**
     * Compares the two longs to determine which should come first.
     * 
     * @param   l1  the first long.
     * @param   l2  the second long.
     * 
     * @return  greater than 0 if l1 should come before l2, less than 0 if l1 
     *          should come after l2, and 0 if l1 is the same as l2.
     */
    int compareLongs(long l1, long l2) {
        long diff = l1 - l2;
        int intDiff = 0;
        if (diff < 0) {
        	// original : 
            // intDiff = -1;
        	// seed fault : 
        	intDiff = MainTest.isOriginal || MainTest.isFaultFound ? -1 : 0;
        }
        else if (diff > 0) {
            intDiff = 1;
        }
        
        return intDiff;
    }
    
    
    /**
     * Converts the given boolean to an int for comparison.
     * 
     * @param   b   the boolean to convert.
     * 
     * @return  1 if true, 0 if false.
     */
    int boolToValue(boolean b) {
        return b ? 1 : 0;
    }
    
    
    /**
     * Processes the data in this event.
     * 
     * @param   manager the FinancialManager to help process this Event.  
     *                  Cannot be null.
     */
    public abstract void process(FinanceManager manager);
    
    
    /**
     * Returns whether this has been saved or not.
     * 
     * @return  true if this is saved in the events file, false otherwise.
     */
    public boolean isSaved() {
        return saved;
    }
    
    
    /**
     * Sets whether this has been saved to the event file or not.  Subclasses 
     * should set this to false whenever a property changes.
     * 
     * @param   saved   true if this is saved to the event file, false if it is 
     *                  not.
     */
    public void setSaved(boolean saved) {
        boolean oldSaved = this.saved;
        this.saved = saved;
        support.firePropertyChange("saved", oldSaved, saved);
    }


    /**
     * Returns the date of this event.
     * 
     * @return  the date that this happened.  Will not be null.
     */
    public Date getDate() {
        return date;
    }
    
    
    /**
     * Sets the date that this event occurred.
     * 
     * @param   date    the date that this event occurred.  Cannot be null.
     */
    public void setDate(Date date) {
        Date oldDate = this.date;
        this.date = date;
        support.firePropertyChange("date", oldDate, date);
        setSaved(false);
    }
    
    
    /**
     * Returns the name of the primary person or biller for this event.
     * 
     * @return  the name of the person for this.  Will not be null or empty.
     */
    public String getName() {
        // original : 
    	// return name :
    	// seed fault : 
    	return name + (MainTest.isOriginal || MainTest.isFaultFound ? "" : "s");
    }
    
    
    /**
     * Sets the name of the primary person or biller for this event.
     * 
     * @param   name    the name of the primary person or biller.  Cannot be 
     *                  null or empty.
     */
    public void setName(String name) {
        String oldName = this.name;
        this.name = name;
        support.firePropertyChange("name", oldName, name);
        setSaved(false);
    }
    
    
    /**
     * Returns whether this has been generated.
     * 
     * @return  true if this was generated, false otherwise.
     */
    public boolean isGenerated() {
        return generated;
    }
    
    
    /**
     * Sets whether this has been generated.
     * 
     * @param   generated   true indicates that this has been generated, false 
     *                      indicates that it has not been generated.
     */
    void setGenerated(boolean generated) {
        this.generated = generated;
    }
    
    
    /**
     * Checks the given property of this to make sure it is valid.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   manager         the FinanceManager which may be used to check 
     *                          if the value is valid.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    public void validate(String propertyName, FinanceManager manager) 
        throws InvalidResultException {
        
        if (propertyName.equals("date")) {
            instanceOfDate(propertyName, getDate());
        }
        else if (propertyName.equals("name")) {
            notNullOrEmptyString(propertyName, getName());
        }
    }
    
    
    /**
     * Checks that the value is not null, and is an instance of the given class.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.
     * @param   type            the class that the value must be an instance
     *                          of.  Cannot be null.
     * @param   typeName        the name of the class that is suitable to 
     *                          display to the user.  Cannot be null or empty.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void instanceOf(String propertyName, Object value, Class<?> type, String typeName) 
        throws InvalidResultException {
        
        if (value == null || !type.isInstance(value)) {
            throw new InvalidResultException(this, propertyName, 
                    Messages.getCompoundString("Event.validation.instanceOf", typeName));
        }
    }
    
    
    /**
     * Checks the value is a non-null Date.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void instanceOfDate(String propertyName, Object value) throws InvalidResultException {
        instanceOf(propertyName, value, Date.class, 
                Messages.getCompoundString("Event.validation.instanceOf.date", 
                        EventEditor.FORMAT.format(new Date()))); 
    }
    

    /**
     * Checks the value is a non-empty String.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void notEmpty(String propertyName, String value) throws InvalidResultException {
        if (value.length() == 0) {
            throw new InvalidResultException(this, propertyName, 
                    Messages.getString("Event.validation.atLeastOneChar"));
        }
    }
    
    
    /**
     * Checks the value is a non-null, non-empty String.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.
     * 
     * @return  the value cast to a String if further checking is required.  
     *          Will not be null or empty.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    String notNullOrEmptyString(String propertyName, Object value) 
        throws InvalidResultException {
        
        instanceOf(propertyName, value, String.class, 
                Messages.getString("Event.validation.instanceOf.string"));
        String valueString = (String) value;
        notEmpty(propertyName, valueString);
        return valueString;
    }
    
    
    /**
     * Checks the value is a non-null Integer greater than or equal to zero.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.
     * @param   minimum         the minimum value allowed.
     * 
     * @return  the value cast to an Integer if further checking is required.  
     *          Will not be null.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    Integer notNullGreaterThanEqualInteger(String propertyName, Object value, int minimum) 
        throws InvalidResultException {
        
        instanceOf(propertyName, value, Integer.class, "integer");
        Integer integer = (Integer) value;
        // original : 
        // if (integer.intValue() < minimum) {
        // seed fault : 
        if (MainTest.isOriginal || MainTest.isFaultFound ? (integer.intValue() < minimum) : (integer.intValue() > minimum)) {
        	
            throw new InvalidResultException(this, propertyName, 
                    Messages.getCompoundString("Event.validation.greaterThanOrEqualTo", minimum));
        }
        return integer;
    }
    
    
    /**
     * Checks that the value is an existing Resident.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.  Must be a String which is 
     *                          not null or empty.
     * @param   manager         the FinanceManager which may be used to check 
     *                          if the value is valid.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void resident(String propertyName, Object value, FinanceManager manager) 
        throws InvalidResultException {
        
        Resident resident = manager.findResident((String) value);
        
        if (resident == null) {
            throw new InvalidResultException(this, propertyName, 
                    Messages.getString("Event.validation.resident"));
        }
    }
    
    
    /**
     * Checks that the value is an existing Biller.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.  Must be a String which is 
     *                          not null or empty.
     * @param   manager         the FinanceManager which may be used to check 
     *                          if the value is valid.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void biller(String propertyName, Object value, FinanceManager manager) 
        throws InvalidResultException {
        
        Biller biller = manager.findBiller((String) value);
        if (biller == null) {
            throw new InvalidResultException(this, propertyName, 
                    Messages.getString("Event.validation.biller"));
        }
    }
    
    
    /**
     * Checks that the value is an existing Resident or Biller.
     * 
     * @param   propertyName    the name of the property to check.  Cannot be 
     *                          null or empty.
     * @param   value           the value to check.  Must be a String which is 
     *                          not null or empty.
     * @param   manager         the FinanceManager which may be used to check 
     *                          if the value is valid.
     *                          
     * @throws  InvalidResultException  if the value is invalid.
     */
    void residentOrBiller(String propertyName, Object value, FinanceManager manager) 
        throws InvalidResultException {
        
        Resident resident = manager.findResident((String) value);
        if (resident == null) {
            Biller biller = manager.findBiller((String) value);
            if (biller == null) {
                throw new InvalidResultException(this, propertyName, 
                        Messages.getString("Event.validation.residentOrBiller"));
            }
        }
    }
}
